package org.example.Frame;

import org.example.Entity.NameInfo;
import org.example.Utill.DatabaseUtil;
import org.example.DAO.impl.ClassInfoDAOImpl;
import org.example.DAO.impl.GroupInfoDAOImpl;
import org.example.DAO.impl.CourseInfoDAOImpl;
import org.example.DAO.impl.NameInfoDAOImpl;
import org.example.Entity.ClassInfo;
import org.example.Entity.GroupInfo;
import org.example.Entity.CourseInfo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.net.URL;
import java.net.MalformedURLException;

public class RollcallFrame extends JFrame {
    private JComboBox<String> classComboBox;
    private JComboBox<String> groupComboBox;
    private JComboBox<String> courseComboBox;
    private JTextArea studentInfoArea;
    private JButton rollButton;
    private Map<String, String> classMap;
    private Map<String, String> groupMap;
    private Map<String, String> courseMap;

    public RollcallFrame() {
        setTitle("随机点名系统");
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        classMap = new HashMap<>();
        groupMap = new HashMap<>();
        courseMap = new HashMap<>();

        // 创建选择班级的下拉框
        classComboBox = new JComboBox<>();
        classComboBox.addItem(""); // 添加空选项
        classComboBox.setPreferredSize(new Dimension(150, 25)); // 设置首选大小，降低高度
        loadClasses();

        // 创建选择小组的下拉框
        groupComboBox = new JComboBox<>();
        groupComboBox.addItem(""); // 添加空选项
        groupComboBox.setPreferredSize(new Dimension(150, 25)); // 设置首选大小，降低高度
        groupComboBox.setEnabled(false); // 初始禁用
        classComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadGroups();
                groupComboBox.setEnabled(true);
                loadCourses();
                courseComboBox.setEnabled(true);
            }
        });

        // 创建选择课程的下拉框
        courseComboBox = new JComboBox<>();
        courseComboBox.addItem(""); // 添加空选项
        courseComboBox.setPreferredSize(new Dimension(150, 25)); // 设置首选大小，降低高度
        courseComboBox.setEnabled(false); // 初始禁用
        groupComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadCourses();
                courseComboBox.setEnabled(true);
            }
        });

        // 结果显示区域
        studentInfoArea = new JTextArea(5, 20);
        studentInfoArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(studentInfoArea);

        // 随机点名按钮
        rollButton = new JButton("随机点名");
        rollButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                rollName();
            }
        });

        // 使用 GridBagLayout 布局
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // 设置控件之间的间距
        gbc.fill = GridBagConstraints.HORIZONTAL;

        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("选择班级:"), gbc);

        gbc.gridx = 1;
        panel.add(classComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("选择小组:"), gbc);

        gbc.gridx = 1;
        panel.add(groupComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("选择课程:"), gbc);

        gbc.gridx = 1;
        panel.add(courseComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(scrollPane, gbc);

        gbc.gridy = 4;
        panel.add(rollButton, gbc);

        add(panel, BorderLayout.CENTER);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                MenuFrame menuFrame = new MenuFrame();
                menuFrame.setVisible(true);
                dispose(); // 关闭窗口
            }
        });
    }

    private void loadClasses() {
        ClassInfoDAOImpl classInfoDAO = new ClassInfoDAOImpl();
        List<ClassInfo> classes = classInfoDAO.getAllClasses();
        for (ClassInfo classInfo : classes) {
            String className = classInfo.getClassName();
            String classId = classInfo.getClassID();
            classComboBox.addItem(className); // 添加班级名称到下拉框
            classMap.put(className, classId); // 将班级名称和ID存入映射
        }
    }

    private void loadGroups() {
        groupComboBox.removeAllItems();
        groupComboBox.addItem("");
        GroupInfoDAOImpl groupInfoDAO = new GroupInfoDAOImpl();
        String selectedClassName = (String) classComboBox.getSelectedItem(); // 获取选中的班级名称
        String selectedClassId = classMap.get(selectedClassName); // 通过班级名称获取班级ID
        List<GroupInfo> groups = groupInfoDAO.getGroupsByClassId(selectedClassId);
        for (GroupInfo groupInfo : groups) {
            String groupName = groupInfo.getGroupName();
            String groupId = groupInfo.getGroupID();
            groupComboBox.addItem(groupName); // 添加小组名称到下拉框
            groupMap.put(groupName, groupId); // 将小组名称和ID存入映射
        }
    }

    private void loadCourses() {
        courseComboBox.removeAllItems();
        courseComboBox.addItem(""); // 添加空选项
        CourseInfoDAOImpl courseInfoDAO = new CourseInfoDAOImpl();
        String selectedClassName = (String) classComboBox.getSelectedItem(); // 获取选中的班级名称
        String selectedClassId = classMap.get(selectedClassName); // 通过班级名称获取班级ID

        if (selectedClassId == null || selectedClassId.isEmpty()) {
            // 处理空或无效的班级ID
            courseComboBox.addItem("无可用课程");
            return;
        }

        List<CourseInfo> courses = courseInfoDAO.getCoursesByClassId(Integer.parseInt(selectedClassId)); // 根据班级ID获取课程
        for (CourseInfo courseInfo : courses) {
            String courseName = courseInfo.getCourseName();
            String courseId = String.valueOf(courseInfo.getCourseId());
            courseComboBox.addItem(courseName); // 添加课程名称到下拉框
            courseMap.put(courseName, courseId); // 将课程名称和ID存入映射
        }
    }

    private void rollName() {
        NameInfoDAOImpl nameInfoDAO = new NameInfoDAOImpl();
        String selectedClassName = (String) classComboBox.getSelectedItem(); // 获取选中的班级名称
        String selectedClassId = classMap.get(selectedClassName); // 通过班级名称获取班级ID
        String selectedGroupName = (String) groupComboBox.getSelectedItem(); // 获取选中的小组名称
        String selectedGroupId = groupMap.get(selectedGroupName); // 通过小组名称获取小组ID
        String selectedCourseName = (String) courseComboBox.getSelectedItem(); // 获取选中的课程名称
        String selectedCourseId = courseMap.get(selectedCourseName); // 通过课程名称获取课程ID

        if (selectedClassId == null || selectedClassId.isEmpty()) {
            studentInfoArea.setText("请先选择班级！");
            return;
        }

        List<NameInfo> studentInfo = null;

        if ((selectedGroupId == null || selectedGroupId.isEmpty()) && 
            (selectedCourseId == null || selectedCourseId.isEmpty())) {
            studentInfo = nameInfoDAO.getStudentNamesByClassId(Integer.parseInt(selectedClassId));
        } else if (selectedGroupId == null || selectedGroupId.isEmpty()) {
            studentInfo = nameInfoDAO.getStudentNamesByCourseId(Integer.parseInt(selectedClassId), Integer.parseInt(selectedCourseId));
        } else if (selectedCourseId == null || selectedCourseId.isEmpty()) {
            studentInfo = nameInfoDAO.getStudentNamesByGroupId(Integer.parseInt(selectedClassId), Integer.parseInt(selectedGroupId));
        } else {
            studentInfo = nameInfoDAO.getRandomStudentInfo(selectedClassId, selectedGroupId, selectedCourseId);
        }

        if (studentInfo == null || studentInfo.isEmpty()) {
            studentInfoArea.setText("当前班级没有学生信息！");
        } else {
            // 随机选择一个学生
            NameInfo randomStudent = studentInfo.get((int) (Math.random() * studentInfo.size()));
            StringBuilder info = new StringBuilder();
            info.append("学号: ").append(randomStudent.getStudentId())
                    .append(", 姓名: ").append(randomStudent.getName()).append("\n");

            // 显示图片
            try {
                URL imageUrl = new URL(randomStudent.getImageUrl());
                ImageIcon imageIcon = new ImageIcon(imageUrl);
                JLabel imageLabel = new JLabel(imageIcon);
                JOptionPane.showMessageDialog(this, imageLabel, "学生图片", JOptionPane.PLAIN_MESSAGE);
            } catch (MalformedURLException e) {
                info.append("图片URL无效！");
            }

            studentInfoArea.setText(info.toString());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RollcallFrame().setVisible(true);
            }
        });
    }
}